/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wb.picmover.handler;

import cn.ac.iie.di.wb.picmover.util.GlobalParameters;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class PicHandler implements Runnable {

    static private final Logger logger = Logger.getLogger(PicHandler.class.getName());

    ThreadPoolExecutor threadpool = null;

    public PicHandler() {
        //创建一个线程池
        threadpool = new ThreadPoolExecutor(GlobalParameters.coreThreadPoolSize, GlobalParameters.maxThreadPoolSize, 3, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(GlobalParameters.blockingQueueSize),
                new ThreadFactory() {
            AtomicInteger idx = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "PicHandlerThreadPoolTask_" + idx.getAndIncrement());
            }
        }, new RejectedExecutionHandler() {

            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                while (true) {
                    try {
                        executor.getQueue().put(r);
                        break;
                    } catch (InterruptedException ex) {
                        logger.warn("", ex);
                    }
                }
            }
        });
    }

    @Override
    public void run() {
        boolean flag = true;
        while (true) {
            try {
                Message dataMes = (Message) GlobalParameters.picHandlerQueue.poll(GlobalParameters.intervaltime, TimeUnit.MILLISECONDS);
                if (dataMes == null) {
                    logger.info("picHandlerQueue doesn't hava available data, and sleep 500 ms.");
                    Thread.sleep(500);
                } else {
                    if (flag) {
                        GlobalParameters.colNames = dataMes.getColNames();
                        GlobalParameters.types = dataMes.getTypes();
                        flag = false;
                        logger.info("get data's colNames and types finish.");
                    }
                    threadpool.execute(new PicThreadPoolTask(dataMes));
                }
            } catch (Exception ex) {
                logger.error("get data from ArrayBlockingQueue failed,cause :" + ex.getMessage(), ex);
            }
        }
    }

}
